package com.vim.common.filter;

import com.alibaba.fastjson.JSONObject;
import com.vim.common.model.response.RestfulResponse;
import com.vim.common.utils.TokenManager;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@WebFilter(urlPatterns = "/**", filterName = "apiFilter")
public class ApiFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        response.addHeader("Access-Control-Allow-Origin", "http://localhost:4001");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "token");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Max-Age", "1800");

        String url = request.getContextPath()+request.getServletPath();

        if(isWhiteUrl(url)){
            //白名单（shiro控制）
            chain.doFilter(request, response);
        }else{
            //API接口（策略控制）
            if(isRequireLogin(url)){
                if(TokenManager.isTokenAvailable(request.getHeader("token"))){
                    chain.doFilter(request, response);
                }else{
                    //token不可用,需要重新登录
                    RestfulResponse result = new RestfulResponse();
                    result.setCode(RestfulResponse.LOGIN_EXPIRE_ERROR);
                    result.setMsg("需要重新登录");
                    response.setCharacterEncoding("utf-8");
                    response.setContentType("text/html;charset=utf-8");
                    response.getWriter().write(JSONObject.toJSONString(result));
                }
            }else{
                chain.doFilter(request, response);
            }
        }
    }

    @Override
    public void destroy() {

    }

    //是否是白名单
    private boolean isWhiteUrl(String url){
        return url.indexOf("/api/") != -1 ? false : true;
    }

    //是否需要登录
    private boolean isRequireLogin(String url){
        StringBuffer sb = new StringBuffer();
        sb.append("/api/user/userInfo").append(",");

        sb.append("/api/shop/order/cartList").append(",");
        sb.append("/api/shop/order/addCart").append(",");
        sb.append("/api/shop/order/delCart").append(",");

        sb.append("/api/shop/order/preOrder").append(",");
        sb.append("/api/shop/order/createOrder").append(",");
        sb.append("/api/shop/order/userOrderList").append(",");

        sb.append("/api/shop/address/userAddressList").append(",");
        sb.append("/api/shop/address/userDefaultAddress").append(",");
        sb.append("/api/shop/address/userAddressDetail").append(",");
        sb.append("/api/shop/address/editUserAddress").append(",");
        if(sb.toString().indexOf(url) != -1){
            return true;
        }
        return false;
    }
}
